package myservice.android.activities;

import java.util.Calendar;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;

public class TimerActivity extends Activity {
	
	private TextView windowTitle;
	private Chronometer timer;
	private Button startStopButton;
	private Button saveButton, resetButton;
	private Button decreaseButton, increaseButton;
	private TextView ministryText;
	
	private boolean timerRunning = false;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.timer);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
        windowTitle = (TextView) findViewById(R.id.titleText);  
        timer = (Chronometer) findViewById(R.id.timer);
        startStopButton = (Button) findViewById(R.id.startStopButton);
        decreaseButton = (Button) findViewById(R.id.decreaseButton);
        increaseButton = (Button) findViewById(R.id.increaseButton);        
        saveButton = (Button) findViewById(R.id.saveButton);
        resetButton = (Button) findViewById(R.id.resetButton);
        ministryText = (TextView) findViewById(R.id.ministryMessage);
        
        windowTitle.setText(Global.res.getString(R.string.title_timer));        
        
        timer.setText("00:00:00");
        
        timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
            	updateDisplay();
            }
        });  
        
        decreaseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				adjustTime(-5);
			}
        }); 
        
        increaseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				adjustTime(5);
			}
        });        
        
        resetButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				timer.setText("00:00:00");
				startStopButton.setText(Global.res.getString(R.string.button_start));
				ministryText.setText(Global.res.getString(R.string.message_start_ministry));
			}
        });
        
        saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				saveTime();
			}
        });        
        
        startStopButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {
				if (timerRunning==false) { // Start timer
					startStopButton.setText(Global.res.getString(R.string.button_stop));
					saveButton.setEnabled(false);
					resetButton.setEnabled(false);
					ministryText.setText(Global.res.getString(R.string.message_in_ministry));				
				    String array[] = timer.getText().toString().split(":");
				    long stoppedMilliseconds = Long.parseLong(array[0]) * 60 * 60 * 1000 + Long.parseLong(array[1]) * 60 * 1000 + Long.parseLong(array[2]) * 1000;
				    timer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);	
				    Database.execSQL("UPDATE settings SET value='"+timer.getBase()+"' WHERE name='timerstart'");
					timer.start();
				} else { // Stop timer
					startStopButton.setText(Global.res.getString(R.string.button_resume));
					saveButton.setEnabled(true);
					resetButton.setEnabled(true);
					ministryText.setText(Global.res.getString(R.string.message_resume_ministry));
					Database.execSQL("UPDATE settings SET value='0' WHERE name='timerstart'");
					timer.stop();
				}
				
				timerRunning=!timerRunning;
				
			}        	
        });
        
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	if (timerRunning==true) {
    		Database.execSQL("UPDATE settings SET value='"+timer.getBase()+"' WHERE name='timerstart'");
    		timer.stop();
    	}
    }    
    
    @Override
    public void onResume() {
    	super.onResume();
    	Cursor cursor = Database.select("SELECT value FROM settings WHERE name='timerstart'");
    	if (cursor.moveToNext()==true) {
    		long base = Long.parseLong(cursor.getString(cursor.getColumnIndex("value")));
    		if (base>0) {
    			
				startStopButton.setText(Global.res.getString(R.string.button_stop));
				saveButton.setEnabled(false);
				resetButton.setEnabled(false);
				ministryText.setText(Global.res.getString(R.string.message_in_ministry));
				timerRunning=true;

    			timer.setBase(base);
    			timer.start();
    		}
    	}
    	cursor.close();
    }
    
    @Override
    public void onBackPressed() {
    	if (timerRunning==false && !timer.getText().equals("00:00:00")) {
    		
    		String array[] = timer.getText().toString().split(":");
    		
    		// Time is less than 1 minute
    		if (Long.parseLong(array[0])==0 && Long.parseLong(array[1])==0) {
    			finish();
    			return;
    		}
    		
    		if (Global.roundDownTimer==true && Long.parseLong(array[0])*60+Long.parseLong(array[1])<5) {
    			Global.displayToast(this, Global.res.getString(R.string.message_time_not_added));    			
    			finish();
    			return;
    		}
    		
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle(Global.res.getText(R.string.title_question));				
			alertDialogBuilder
				.setMessage(Global.res.getText(R.string.message_time_save_confirmation))
				.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						saveTime();
					}
				  })
				.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
	 
			AlertDialog alertDialog = alertDialogBuilder.create();
			alertDialog.show();				
    	} else
    		super.onBackPressed();
    }    
    
    private void adjustTime(int deltaMinutes) {
	    String array[] = timer.getText().toString().split(":");
	    long stoppedMilliseconds = Long.parseLong(array[0]) * 60 * 60 * 1000 + Long.parseLong(array[1]) * 60 * 1000 + Long.parseLong(array[2]) * 1000;
	    stoppedMilliseconds = stoppedMilliseconds + deltaMinutes * 60000;
	    if (stoppedMilliseconds<0)
	    	stoppedMilliseconds=0;
	    timer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);    
	    
        updateDisplay();	    
	    
    }
    
    private void updateDisplay() {
        CharSequence text = timer.getText();
        if (text.length()  == 5) {
            timer.setText("00:"+text);
        } else if (text.length() == 7) {
            timer.setText("0"+text);
        }    	
    }
    
    private void saveTime() {
    	
    	if (timer.getText().equals("00:00:00")) {
    		finish();
    		return;
    	}
    	
	    String array[] = timer.getText().toString().split(":");
	    int hours = Integer.parseInt(array[0]);
	    int minutes = Integer.parseInt(array[1]);
	    
	    if (Global.roundDownTimer==true && hours*60+minutes<5) {
		    Global.displayToast(this, Global.res.getString(R.string.message_time_not_added));	    	
	    	finish();
	    	return;
	    }
	    
	    if (Global.roundDownTimer==true) // Round minutes down to a whole multiple of 5
	    	minutes = minutes / 5 * 5;
	    
	    Calendar today = Calendar.getInstance();
	    int year = today.get(Calendar.YEAR);
	    int month = today.get(Calendar.MONTH);
	    int date = today.get(Calendar.DATE);
	    
	    if (hours+minutes>0) {	    	
	    	
	    	Cursor cursor = Database.select("SELECT hours,minutes FROM ministry WHERE year="+year+" AND month="+month+" AND date="+date);
	    	if (cursor.moveToNext()==true) { // Ministry data for today already exist; need to be updated 
	    		hours = hours + cursor.getInt(cursor.getColumnIndex("hours"));
	    		minutes = minutes + cursor.getInt(cursor.getColumnIndex("minutes"));
	    		if (minutes>59) {
	    			minutes=minutes-60;
	    			hours++;
	    		}
	    		Database.execSQL("UPDATE ministry SET hours="+hours+", minutes="+minutes+", timestamp="+Global.getTimeStamp()+" WHERE year="+year+" AND month="+month+" AND date="+date);

	    	} else { // Ministry data for today does not exist; need to create the record
	    		Database.execSQL("INSERT INTO ministry (date, month, year, hours, minutes, chours, cminutes, magazines, brochures, books, returncalls, comments, timestamp) "+
	    					     "VALUES ("+date+","+month+","+year+","+hours+","+minutes+",0,0,0,0,0,0,'',"+Global.getTimeStamp()+")");
	    	}
    		cursor.close();
    	
    	    Global.displayToast(this, Global.res.getString(R.string.message_time_added));
	    }	    
	    
    	finish();
    }
    
}
